package com.devilwwj.http.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by devilwwj on 15/7/26.
 */
public class RequestManager {
    private static RequestManager mInstance;
    private HashMap<String, ArrayList<Request>> mCechedRequest;
    private final ExecutorService mExecutors;


    public static RequestManager getInstance() {
        if (mInstance == null) {
           mInstance = new RequestManager();
        }
        return mInstance;
    }

    public RequestManager() {
        mCechedRequest = new HashMap<String, ArrayList<Request>>();
        mExecutors = Executors.newFixedThreadPool(5);
    }

    /**
     *
     * @param request
     */
    public void performRequest(Request request) {
        request.execute(mExecutors);
        if (!mCechedRequest.containsKey(request.tag)) {
            ArrayList<Request> requests = new ArrayList<Request>();
            mCechedRequest.put(request.tag, requests);
        }
        mCechedRequest.get(request.tag).add(request);

    }

    public void cancelRequest(String tag) {
        cancelRequest(tag, false);
    }

    public void cancelRequest(String tag, boolean force) {
        if (tag == null || "".equals(tag.trim())) {
            return;
        }
        // TODO find requests by tag, and cancel them
        if (mCechedRequest.containsKey(tag)) {
            ArrayList<Request> requests = mCechedRequest.remove(tag);
            for (Request request : requests) {
                if (!request.isCancelled && tag.equals(request.tag)) {
                    request.cancel(force);
                }
            }
        }
    }

    public void cancelAll() {
        for (Map.Entry<String, ArrayList<Request>> entry : mCechedRequest.entrySet()) {
            ArrayList<Request> requests = entry.getValue();

            for (Request request : requests) {
                if (!request.isCancelled) {
                    request.cancel(true);
                }
            }
        }
    }
}
